-module(dict_server).
-behaviour(gen_server).
-export([start_link/1,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).

start_link(Name) ->
	gen_server:start_link({local,Name},?MODULE, [], []).
init(_) ->
	{ok,{running,dict:new()}}.
	
handle_call({get,Key},_,{running,Dict}) ->
	{reply,retrive(Key,Dict),{running,Dict}};


handle_call({add,{Key,Val}},_,{running,Dict}) ->
	{ok,New_Dict} = add(Key,Val,Dict),
	{reply,ok,{running,New_Dict}};
	
handle_call({erase,Key},_,{running,Dict}) ->
	{reply,ok,{running,dict:erase(Key,Dict)}};
	
handle_call(Req,_,State) ->
	io:format("wrong request ~p ~n",[Req]),
	{reply, {error,"no func define"}, State}.
	
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.

erase(Key,Dict) ->
	dict:erase(Key,Dict).
	
retrive(Key,Dict) ->
	try
		dict:fetch(Key,Dict)
	of
		Val -> Val
	catch
		_:_ ->
			unknown
	end.
add(Key,Value,Dict) ->
	{ok,dict:store(Key, Value, Dict)}.